using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using QQZiFramework;
using QQZiFramework.Mvc;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace QQZiCore.Mvc.Controllers
{
    [UnCatchError]
    [ApiController]
    [Route("{OEM}/[controller]/[action]")]
    [DefaultAccessLog]
    public class BaseController : QQZiFramework.Mvc.QQZiApiController
    {
        [NonAction]
        protected override string GetQueryEntityName()
        {
            string entityName = GetParamValue<string>("entityName",true);
            if (entityName.IndexOf(",") == -1)
            {
                entityName += ",QQZiCore.SH3H.Modals";
            }
            return entityName;
        }



        // [LoginCheckFilter(IsCheck = false)]
        // public ContentResult OEMJS()
        // {
        //     using (DBContext context = CreateDBContext())
        //     {
        //         OEMInfo oem = CurrentOEM;
        //         System.Text.StringBuilder sb = new System.Text.StringBuilder();
        //         sb.AppendLine(string.Format("var oem={{Name:\"{0}\",Title:\"{1}\"}};", oem.Name, oem.Title));
        //         //sb.AppendLine("alert(oem.Title)");
        //         return Content(sb.ToString(), "application/x-javascript");
        //     }
        // }
        DBContext _dbcontext;
        /// <summary>
        /// 创建DBContext，如果一个过程已经创建则直接返回实例
        /// </summary>
        /// <returns></returns>
        [NonAction]
        public override DBContext CreateDBContext()
        {
            if (_dbcontext != null) return _dbcontext;
            string oem = this.RouteData.Values["OEM"] as string;
            return CreateOEMContext(oem);
        }

        protected DBContext CreateOEMContext(string oem)
        {
            if (_dbcontext != null) return _dbcontext;
            if (oem == null) throw new NotAlowAccessException();
            oem = oem.ToUpper();
            OEMMemberShip memberShip = OEMMemberShip.GetInstance(oem);
            _dbcontext = memberShip.CreateDBContext();
            memberShip.SetContextArgs(_dbcontext, HttpContext);
            _dbcontext.FormatDataSource = GetDBContextFormatSource();
            return _dbcontext;
        }
        Hashtable hashtable;
        protected override Hashtable GetDBContextFormatSource()
        {

            if (hashtable != null) return hashtable;
            hashtable = base.GetDBContextFormatSource();
            string currentOem = this.RouteData.Values["OEM"] as string;
            currentOem = currentOem.ToUpper();
            foreach (var oem in OEMMemberShip.OEMList)
            {
                if (oem.Name.StartsWith(currentOem + "-"))
                {
                    string dbName = Utility.getMiddle(oem.GetConnectionString(), "Catalog=", ";");
                    hashtable.Add("DATABASE_" + oem.ExtName.ToUpper(), "[" + dbName + "]");
                }
            }
            //将OEM-Ext里面其它的几个数据库名称放到FormatDataSource里面
            return hashtable;
        }

        /// <summary>
        /// 通用Permission查询
        /// </summary>
        [QQZiFramework.Mvc.LoginCheckFilter(IsCheck = false, CheckPermission = null)]
        [HttpPost]
        public override string DoQuery(string permission, string entityName, string queryField, string whereField, string orderBy, int pageIndex, int pageSize, string groupByFields)
        {

            return base.DoQuery(permission, entityName, queryField, whereField, orderBy, pageIndex, pageSize, groupByFields);
        }

        /// <summary>
        /// 能用Permission查询单个对象，以实体形式返回
        /// </summary>

        [QQZiFramework.Mvc.LoginCheckFilter(IsCheck = false, CheckPermission = null)]
        [HttpPost]
        public override string DoGetOne(string permission, string entityName, string queryField, string primaryVal)
        {
            return base.DoGetOne(permission, entityName, queryField, primaryVal);
        }


        // protected virtual void OnQuerying(QueryParam param, DBContext db)
        // {

        // }



        protected string JM(object result)
        {
            return (new JsonMessage() { Result = result }).ToJson();
        }



    }

    public class WapResponse<T> : IActionResult
    {
        public int Code { get; set; }

        public int StatusCode { get; set; }

        public string Message { get; set; }

        [Newtonsoft.Json.JsonProperty("data")]
        public T Data { get; set; }

        public WapResponse(string msg)
        {
            Code = -1;
            StatusCode = 500;
            Message = msg;
        }
        public WapResponse(Exception ex)
        {
            Code = -1;
            StatusCode = 500;
            Message = ex.Message;
        }


        public WapResponse(T data)
        {
            StatusCode = 200;
            Code = 0;
            Data = data;
        }



        public Task ExecuteResultAsync(ActionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            HttpResponse response = context.HttpContext.Response;
            response.ContentType = "application/json";
            Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings() { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore };
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(this, settings);
            return response.WriteAsync(json);
        }
    }
}